# coding:utf-8
"""
Created on 2018/4/17

@author: lby
"""
SESSION_NAME = "session:%s"


class SessionManager(object):
    def __init__(self, redis):
        self.redis = redis

    def set_session(self, sessionid, identifier, ctx, expires=86400):
        self.redis.hset(SESSION_NAME % str(sessionid), identifier, ctx)
        if expires:
            self.redis.expire(SESSION_NAME % str(sessionid), int(expires))

    def set_mapping_session(self, sessionid, mapping, expires=86400):
        self.redis.hmset(SESSION_NAME % str(sessionid), mapping)
        if expires:
            self.redis.expire(SESSION_NAME % str(sessionid), int(expires))

    def get_session(self, sessionid, identifier):
        ctx = self.redis.hget(SESSION_NAME % str(sessionid), identifier)
        return ctx

    def clear(self, sessionid, identifier):
        self.redis.hdel(SESSION_NAME % str(sessionid), identifier)

    def clear_all(self, sessionid):
        self.redis.delete(SESSION_NAME % str(sessionid))